package com.example.module_a;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.example.module_a.rxjava.RxUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class MainActivity extends AppCompatActivity {

    private static Disposable disposable;
    @BindView(R.id.tv_send_code)
    TextView tvSendCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.tv_send_code)
    public void onViewClicked() {
        countDo();
    }

    private void countDo() {
        new RxUtils()
                .cutDown(10)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //开始发射数据时 初始化空间状态
                        tvSendCode.setEnabled(false);
                    }
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                MainActivity.disposable = d;
            }

            @Override
            public void onNext(Long aLong) {
                tvSendCode.setText(aLong + "秒后重发");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                //结束时重置状态
                tvSendCode.setEnabled(true);
                tvSendCode.setText("发送验证码");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            disposable.dispose();
        }
    }
}
